package com.hehe.controller;


import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ArticleController {

    @Resource
    private ArticleRepository articleRepository;

    @GetMapping("article_list")
    public String listArticles(
            @RequestParam(value = "page", defaultValue = "0") int page,
            Model model) {

        final int PAGE_SIZE = 5; // 每页默认显示的文章数
        int currentPage = Math.max(0, page);   // 创建 Pageable 对象 , Spring Data JPA 的页码从 0 开始
        Pageable pageable = PageRequest.of(currentPage, PAGE_SIZE); // 创建分页请求对象 (0-based page number)
        Page<T_article> articlePage = articleRepository.findByOrderByTitleAsc(pageable);

        // 获取总页数
        int totalPages = articlePage.getTotalPages();

        // 3. **处理页码越界问题**
        // 如果请求的页码大于等于总页数（且总页数大于 0），则将其重置为最后一页
        if (totalPages > 0 && currentPage >= totalPages) {
            currentPage = totalPages - 1;
            // 重新查询最后一页数据
            pageable = PageRequest.of(currentPage, PAGE_SIZE);
            articlePage = articleRepository.findAll(pageable);
        } else if (totalPages == 0) {
            // 如果没有数据，确保 currentPage 仍为 0
            currentPage = 0;
        }

        List<T_article> articles = articlePage.getContent();

        model.addAttribute("articles", articles);        // 当前页的文章列表
        model.addAttribute("currentPage", currentPage);  // 当前页码 (0-based)
        model.addAttribute("totalPages", totalPages);    // 总页数

        return "index.html";

    }
}


